import React, { Fragment } from 'react'
import { View, StyleSheet, Text } from 'react-native'
import { ScaleS, ScaleT, STATUSBAR_HEIGHT, NAVIGATIONBAR_NAVIGATION_HEIGHT } from 'src/utils/ScreenUtil'
import { connect } from 'react-redux'
import { UPDATE_IM } from 'src/store/actions/im'
import BasePage from 'src/pageP/base/base-page/index'
import CompanyApplyNotComplete from '../../main/main-page/components/CompanyApplyNotComplete'
import { TabBar, TabView } from 'react-native-tab-view'
import NotifyComponent from 'src/pageB/message/message-page/components/NotifyComponent'
import MessageComponent from 'src/pageB/message/message-page/components/MessageComponent'
import CustomButton from 'src/components/button/CustomButton'
import { updateMessageList } from 'src/utils/RequestAPI'

const mapActiontoProps = dispatch => ({
  updateImState (payload) {
    dispatch({
      type: UPDATE_IM,
      payload: {
        ...payload
      }
    })
  }
})

@connect(
  ({ userinfo, im }) => ({
    userinfo,
    role: userinfo.role,
    ...im
  }),
  mapActiontoProps
)
class MessagePage extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: null,
      index: 0,
      routes: [
        { key: 'message', title: '消息' },
        { key: 'notify', title: '通知' }
      ],
      notifyRedDot: false,
      notifyIds: []
    }
  }

  childRender () {
    const { navigation } = this.props
    return (
      <Fragment>
        <View style={styles.container}>
          <TabView
            style={styles.tabView}
            navigationState={this.state}
            renderScene={this._renderScene}
            onIndexChange={this._onIndexChange}
            renderTabBar={this._renderTabBar}
            swipeEnabled={false}
          />
        </View>
        <CompanyApplyNotComplete
          navigation={navigation}
        />
      </Fragment>
    )
  }

  componentWillFocus () {
    const { notifyIds, routes, index } = this.state
    notifyIds.length && this.hasRedNotify(notifyIds, routes[index].key)
  }

  /**
   * 渲染每一个屏
   * @param route
   * @param jumpTo
   * @returns {*}
   * @private
   */
  _renderScene = ({ route, jumpTo }) => {
    switch (route.key) {
      case 'message':
        return this._renderMessageComponent()
      case 'notify':
        return this._renderNotifyComponent()
    }
  }

  /**
   * 渲染消息
   * @returns {*}
   * @private
   */
  _renderMessageComponent = () => {
    const { contactList, updateImState, userinfo: { userId, B: { userId: realUserId } }, navigation } = this.props
    return (
      <MessageComponent
        messageList={contactList}
        updateImState={updateImState}
        navigatePage={'ChatPageB'}
        userId={userId}
        realUserId={realUserId}
        navigation={navigation}
        notLoginTip={'登录后才可与人才沟通哦～'}/>
    )
  }

  /**
   * 渲染通知
   * @returns {*}
   * @private
   */
  _renderNotifyComponent = () => {
    const { userinfo: { userId }, navigation, role } = this.props
    return (
      <NotifyComponent
        userId={userId}
        navigation={navigation}
        role={role}
        readNotify={this.hasRedNotify}/>
    )
  }

  hasRedNotify = (ids, key = '') => {
    const { index, routes } = this.state
    this.setState({
      notifyIds: ids
    })
    if (key === 'notify' || routes[index].key === 'notify') {
      if (ids.length > 0) {
        updateMessageList({ params: { ids: ids.join(',') } }).then(() => {
          this.setState({
            notifyRedDot: false
          })
        })
      } else {
        this.setState({
          notifyRedDot: false
        })
      }
    } else {
      this.setState({
        notifyRedDot: ids.length > 0
      })
    }
  }

  /**
   * 渲染tabBar
   * @param props
   * @returns {*}
   * @private
   */
  _renderTabBar = (props) => {
    const { navigationState: { index, routes }, isRed } = props
    const { notifyRedDot } = this.state
    return (
      <View style={styles.tabContainer}>
        <CustomButton style={styles.tabItem} onPress={this._tabBarClick} params={{ props, key: routes[0].key }}>
          {isRed && <View style={styles.redDot}></View>}
          <Text style={[styles.tabItemText, index === 0 && styles.tabItemActive]}>{routes[0].title}</Text>
          {index === 0 ? <View style={styles.tabItemDot}></View> : <View style={[styles.tabItemDot, { backgroundColor: 'transparent' }]}></View>}
        </CustomButton>
        <CustomButton style={styles.tabItem} onPress={this._tabBarClick} params={{ props, key: routes[1].key }}>
          {notifyRedDot && <View style={styles.redDot}></View>}
          <Text style={[styles.tabItemText, index === 1 && styles.tabItemActive]}>{routes[1].title}</Text>
          {index === 1 ? <View style={styles.tabItemDot}></View> : <View style={[styles.tabItemDot, { backgroundColor: 'transparent' }]}></View>}
        </CustomButton>
      </View>
    )
  }

  _tabBarClick = ({ props, key }) => {
    const { jumpTo, navigationState: { index, routes } } = props
    jumpTo(key)
    const { notifyIds } = this.state
    this.hasRedNotify(notifyIds, key)
  }

  // _renderTabBar = (props) => {
  //   return (
  //     <TabBar
  //       {...props}
  //       style={styles.tabBarStyle}
  //       tabStyle={{ width: 'auto' }}
  //       renderLabel={this._renderLabel}
  //       indicatorStyle={{ backgroundColor: 'white' }}
  //     />
  //   )
  // }

  /**
   * 渲染标签
   * @param route
   * @param focused
   * @param color
   * @returns {*}
   * @private
   */
  _renderLabel = ({ route, focused, color }) => {
    return (
      <View style={styles.labelItemView}>
        <Text style={[{ color }, styles.labelItem, focused ? styles.activeText : styles.inactiveText]}>
          {route.title}
        </Text>
      </View>
    )
  }

  /**
   * 切换标签
   * @param index
   * @private
   */
  _onIndexChange = (index) => {
    this.setState({ index })
  }
}

export default MessagePage

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: STATUSBAR_HEIGHT,
    height: NAVIGATIONBAR_NAVIGATION_HEIGHT
  },
  tabView: {
    flex: 1
  },
  tabBarStyle: {
    backgroundColor: 'white'
  },
  labelItemView: {
    width: ScaleS(80),
    height: ScaleS(30),
    paddingLeft: ScaleS(22),
    justifyContent: 'center',
    alignItems: 'center'
  },
  activeText: {
    color: '#000000',
    fontSize: ScaleT(25),
    fontWeight: '600'
  },
  inactiveText: {
    color: '#CCCCCC',
    fontSize: ScaleT(21),
    fontWeight: '400'
  },
  tabContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: ScaleS(20),
    height: NAVIGATIONBAR_NAVIGATION_HEIGHT
  },
  tabItem: {
    marginRight: ScaleS(29),
    flexDirection: 'column',
    justifyContent: 'flex-start',
    alignItems: 'center'
  },
  tabItemText: {
    fontSize: ScaleT(17),
    fontWeight: '500',
    color: '#CCCCCC'
  },
  tabItemDot: {
    width: ScaleS(9),
    height: ScaleS(2),
    borderRadius: ScaleS(3),
    backgroundColor: '#3c3c3c',
    marginTop: ScaleS(8)
  },
  tabItemActive: {
    fontSize: ScaleT(16),
    fontWeight: '500',
    color: '#3C3C3C'
  },
  redDot: {
    position: 'absolute',
    right: ScaleS(-8),
    width: ScaleS(6),
    height: ScaleS(6),
    backgroundColor: '#FF6B6B',
    borderRadius: ScaleS(3)
  }
})
